package com.itheima.reggie.filter;


import com.itheima.reggie.bean.Employee;
import com.itheima.reggie.uitls.BaseContext;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * 登录权限校验过滤器
 * 1. 定义类，实现接口Filter
 * 2. 实现方法 doFilter
 * 3. 注册过滤器 ，在类上打上注解 @WebFilter("/*")
 * 4. 在springboot环境下，要想让过来器生效，需要在启动类上加上注解 @ServletComponentScan
 */
@WebFilter("/*")
public class LoginCheckFilter implements Filter {

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {


        //获取请求路径
        HttpServletRequest req = (HttpServletRequest) servletRequest;
        HttpServletResponse resp = (HttpServletResponse) servletResponse;


        String requestPath = req.getRequestURI();
        System.out.println("requestPath = " + requestPath);

        //2. 判断请求地址是否属于直接放行的地址
        if (requestPath.contains("login") || requestPath.contains("logout")
                || requestPath.endsWith(".js") || requestPath.endsWith(".css") || requestPath.contains("images")
                || requestPath.contains("element") || requestPath.contains("ico") || requestPath.contains("smscode")) {
            //直接放行！
            filterChain.doFilter(servletRequest, servletResponse);
            return;
        }

        //3. 如果不属于以上直接放行的路径，那么就要判断是否有登录。
        Employee employee = (Employee) req.getSession().getAttribute("employee");

        //3.1 管理员登录判断是否有值
        if (employee != null) {

            //走到这里说明存储有值,在这里存储id
            BaseContext.set(employee.getId());

            //直接放行！
            filterChain.doFilter(servletRequest, servletResponse);
            return;
        }

            //3.2 如果等于空，那么即表示没有登录，没有登录，就要跳转到登录页面去！
            resp.sendRedirect("/backend/page/login/login.html");

    }


}
